<script setup>
import {ElMessage, ElMessageBox, ElTooltip} from 'element-plus';
import { ref, onMounted, watch } from 'vue';
import {getChatHistory, deleteChatHistory, deleteAllChatHistories} from '@/api/chat';
import { useTokenStore } from '@/stores/token';

const tokenStore = useTokenStore();
const conversations = ref([]);
const currentConversationId = ref(null);

const emit = defineEmits([
  'new-conversation',
  'delete-all',
  'switch-conversation'
]);

const isCollapsed = ref(false);

const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};

// 生成随机会话ID
const generateChatId = () => {
  return Math.random().toString(36).substr(2, 9);
};

// 获取会话标题（UUID后6位）
const getShortTitle = (chatId) => {
  if (!chatId) return '新对话';
  return chatId.substr(-6).toUpperCase();
};

// 获取会话列表
const fetchSessions = async () => {
  try {
    const chatHistories = await getChatHistory('chat');
    conversations.value = (chatHistories.data || []).map(item => ({
      id: item.chatId,
      title: item.title || `对话 ${getShortTitle(item.chatId)}`,
      chatId: item.chatId,
      updatedAt: item.updatedAt ? new Date(item.updatedAt).toLocaleString() : ''
    }));

    // 默认选中第一个会话
    if (conversations.value.length > 0 && !currentConversationId.value) {
      currentConversationId.value = conversations.value[0].chatId;
      emit('switch-conversation', conversations.value[0]);
    }
  } catch (error) {
    console.error('获取会话列表失败:', error);
    ElMessage.error('获取会话列表失败！');
  }
};

// 新建会话
const newConversation = () => {
  for (let item of conversations.value){
    console.log(item)
    if (!item.hasOwnProperty('updatedAt')){
      return
    }
  }
  const chatId = generateChatId();
  const newConv = {
    id: chatId,
    title: `对话 ${getShortTitle(chatId)}`,
    chatId,
    lastTime: new Date().toLocaleString()
  };

  conversations.value.unshift(newConv);
  currentConversationId.value = chatId;
  emit('new-conversation', newConv);
};

// 删除所有会话
const deleteAllConversations = async () => {
  try {
    ElMessageBox.confirm(
        '确定要删除所有会话吗？所有会话和消息将被永久删除，此操作不可恢复。',
        '删除确认',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning',
          confirmButtonClass: 'el-button--danger'
        }
    ).then(async () => {
      // 调用删除所有API
      await deleteAllChatHistories('chat');

      // 清空会话列表
      conversations.value = [];
      currentConversationId.value = null;

      // 触发删除所有事件
      emit('delete-all');

      ElMessage.success('所有会话已删除');
    }).catch(() => {});
  } catch (error) {
    console.error('删除所有会话失败:', error);
    ElMessage.error('删除所有会话失败: ' + (error.response?.data?.message || error.message));
  }
};

// 添加删除会话方法
const deleteConversation = async (chatId) => {
  try {
    ElMessageBox.confirm(
        '确定要删除此会话吗？所有相关消息将被永久删除。',
        '删除确认',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning',
          confirmButtonClass: 'el-button--danger'
        }
    ).then(async () => {
      // 调用删除API
      await deleteChatHistory('chat', chatId);

      // 从列表中移除
      conversations.value = conversations.value.filter(
          conv => conv.chatId !== chatId
      );

      // 如果删除的是当前会话，重置状态
      if (currentConversationId.value === chatId) {
        currentConversationId.value = null;
        emit('switch-conversation', null);
      }
      ElMessage.success('会话已删除');

      // 删除成功后触发事件
      emit('delete-conversation', chatId);
    }).catch(() => {});
  } catch (error) {
    console.error('删除会话失败:', error);
    ElMessage.error('删除会话失败: ' + (error.response?.data?.message || error.message));
  }
};

// 切换会话
const switchConversation = (conversation) => {
  currentConversationId.value = conversation.chatId;
  emit('switch-conversation', conversation);
};

onMounted(() => {
  if (tokenStore.token) {
    fetchSessions();
  }
});

// 监听token变化（登录/登出时重新获取会话）
watch(() => tokenStore.token, (newToken) => {
  if (newToken) {
    fetchSessions();
  } else {
    conversations.value = [];
    currentConversationId.value = null;
  }
});

defineExpose({
  fetchSessions
})
</script>

<template>
  <div class="history-container" v-if="!isCollapsed">
    <div class="history-header">
      <div class="history-title">历史对话</div>
      <div class="history-actions">
        <div class="history-action" @click="newConversation">
          <ElTooltip content="新建对话" placement="bottom">
            <i class="fas fa-plus"></i>
          </ElTooltip>
        </div>
        <div class="history-action" @click="deleteAllConversations">
          <ElTooltip content="删除所有" placement="bottom">
            <i class="fas fa-trash"></i>
          </ElTooltip>
        </div>
        <div class="history-action" @click="toggleCollapse">
          <ElTooltip content="向右折叠" placement="bottom">
            <i class="fas fa-chevron-right"></i>
          </ElTooltip>
        </div>
      </div>
    </div>

    <div class="history-list">
      <div
          v-for="conversation in conversations"
          :key="conversation.id"
          class="history-item"
          :class="{ active: conversation.chatId === currentConversationId }"
          @click="switchConversation(conversation)"
      >
        <div class="title">{{ conversation.title }}</div>
        <div class="date">最后活动: {{ conversation.updatedAt }}</div>
        <!-- 添加删除按钮 -->
        <div class="delete-btn" @click.stop="deleteConversation(conversation.chatId)">
          <ElTooltip content="删除会话" placement="top">
            <i class="fas fa-trash-alt"></i>
          </ElTooltip>
        </div>
      </div>

      <div v-if="conversations.length === 0" class="empty-history">
        <i class="fas fa-comments"></i>
        <p>暂无历史对话</p>
      </div>
    </div>
  </div>

  <div class="history-container-collapsed" v-else>
    <div class="collapse-trigger" @click="toggleCollapse">
      <ElTooltip content="展开历史记录" placement="bottom">
        <i class="fas fa-chevron-left"></i>
      </ElTooltip>
    </div>
  </div>
</template>

<style scoped>
.history-container {
  width: 300px;
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
}

.history-container-collapsed {
  width: 50px;
  height: 100vh;
  margin-right: 0;
  background: rgb(170, 168, 168);
  position: fixed;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 1000;
  transition: all 0.3s ease;
}

.collapse-trigger {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  margin-left: 9px;
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #6c757d;
  background: #f8f9fa;
  transition: all 0.2s ease;
}

.collapse-trigger:hover {
  background-color: #4895ef;
  color: white;
}

.history-header {
  padding: 20px;
  border-bottom: 1px solid #dee2e6;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--theme);
}

.history-actions {
  display: flex;
  gap: 12px;
}

.history-action {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #6c757d;
  background: #f8f9fa;
  transition: all 0.2s ease;
}

.history-action:hover {
  background: #4895ef;
  color: white;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.history-item {
  padding: 14px;
  border-radius: 10px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  background: var(--contact-bg);
  border: 1px solid #dee2e6;
  color: var(--txcolor);
}

.history-item:hover {
  background: #e6eeff;
  color: #0e0e0e;
  border-color: #4895ef;
}

.history-item.active {
  background: #e3f2fd;
  color: #0e0e0e;
  border-color: #4361ee;
}

.history-item .title {
  font-weight: 500;
  margin-bottom: 5px;
  font-size: 14px;
}

.history-item .date {
  font-size: 12px;
  color: #6c757d;
}

.history-item .keywords {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-top: 8px;
}

.empty-history {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #6c757d;
  text-align: center;
  padding: 20px;
}

.empty-history i {
  font-size: 48px;
  margin-bottom: 15px;
  color: #dee2e6;
}

.empty-history p {
  font-size: 14px;
}

/* 添加删除按钮样式 */
.history-item {
  position: relative;
  padding-right: 40px; /* 为删除按钮留出空间 */
}

.delete-btn {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #f56c6c;
  cursor: pointer;
  opacity: 0.5;
  transition: all 0.3s;
  border-radius: 4px;
}

.delete-btn:hover {
  opacity: 1;
  background-color: #fef0f0;
}

.history-item:hover .delete-btn {
  opacity: 0.8;
}
</style>